package com.lanxiaoye.shoppingSystem.web;

import com.lanxiaoye.shoppingSystem.common.Constants;
import com.lanxiaoye.shoppingSystem.common.result.RequestResult;
import com.lanxiaoye.shoppingSystem.component.ComparatorRecord;
import com.lanxiaoye.shoppingSystem.entity.*;
import com.lanxiaoye.shoppingSystem.service.GoodsService;
import com.lanxiaoye.shoppingSystem.service.ModuleService;
import com.lanxiaoye.shoppingSystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/3/21.
 */
@Controller
@RequestMapping("/home")
public class HomePageController extends BaseController {

    @Autowired
    UserService userService;

    @Autowired
    ModuleService moduleService;

    @Autowired
    GoodsService goodsService;

    @RequestMapping("/item")
    public String theme(String userId,String item,Model model){
        User user = userService.getUserById(Integer.parseInt(userId));
        List<ReceiptInfo> receiptInfoList = moduleService.getReceiptInfo(user.getUserId());
        List<Category> categoryList = moduleService.getAllCategory();
        List<Goods> topSalesList = goodsService.getTopSalesEight();
        List<ShoppingCar> shoppingCarList = moduleService.getCartsByUserId(user.getUserId());
        List<Goods> shoppingCarGoodsList = new ArrayList<>();
        for (ShoppingCar shoppingCar:shoppingCarList
             ) {
            Goods goods = goodsService.getByGoodsId(shoppingCar.getGoodsId());
            shoppingCarGoodsList.add(goods);
        }
        List<ScanRecord> scanRecordList = moduleService.getRecentScan(user.getUserId());
        //将scanRecordList按浏览次数排序
        ComparatorRecord comparator = new ComparatorRecord();
        Collections.sort(scanRecordList,comparator);

        List<Goods> scanRecordGoodsList = new ArrayList<>();
        for (ScanRecord scanRecord:scanRecordList
                ) {
            Goods goods = goodsService.getByGoodsId(scanRecord.getGoodsId());
            scanRecordGoodsList.add(goods);
        }
        List<UserOrder> orderList = moduleService.getOrderByUserId(user.getUserId());
        List<Goods> orderGoodsList = new ArrayList<>();
        for (UserOrder userOrder:orderList
             ) {
            Goods goods = goodsService.getByGoodsId(userOrder.getGoodsId());
            orderGoodsList.add(goods);
        }

        model.addAttribute("User",user);
        model.addAttribute("ReceiptInfoList",receiptInfoList);
        model.addAttribute("CategoryList",categoryList);
        model.addAttribute("TopSalesList",topSalesList);
        model.addAttribute("ShoppingCarList",shoppingCarList);
        model.addAttribute("ShoppingCarGoodsList",shoppingCarGoodsList);
        model.addAttribute("ScanRecordGoodsList",scanRecordGoodsList);
        model.addAttribute("OrderList",orderList);
        model.addAttribute("OrderGoodsList",orderGoodsList);

        String url = "/home/" + item;
        return url;
    }

    @RequestMapping("/category")
    @ResponseBody
    public List<Goods> categoryGoods(HttpServletRequest request){
        String categoryId = request.getParameter("categoryId");
        List<Goods> goodsList = goodsService.getByCategoryId(Integer.parseInt(categoryId));
        return goodsList;
    }

    @RequestMapping("/search")
    @ResponseBody
    public List<Goods> searchGoods(HttpServletRequest request){
        String keyword = request.getParameter("keyword");
        List<Goods> goodsList = goodsService.getSearchGoods(keyword);
        return goodsList;
    }

    @RequestMapping("/goodsDetail")
    public String goodsDetail(String goodsId ,String userId , Model model){
        Goods goods = goodsService.getByGoodsId(Integer.parseInt(goodsId));
        User user = userService.getUserById(Integer.parseInt(userId));
        //List<Category> categoryList = moduleService.getAllCategory();
        List<Comment> commentList = moduleService.getGoodsComment(Integer.parseInt(goodsId));
        //保存浏览记录
        ScanRecord scanRecord = new ScanRecord();
        scanRecord.setUserId(user.getUserId());
        scanRecord.setGoodsId(goods.getGoodsId());
        ScanRecord scanRecord1 = moduleService.getRecordByUserAndGoods(user.getUserId(),goods.getGoodsId());
        if(scanRecord1 == null){
            scanRecord.setScanNum(1);
            scanRecord.setCreateTime(String.valueOf(new Date().getTime()));
            scanRecord.setUpdateTime(scanRecord.getCreateTime());
            moduleService.addScanRecord(scanRecord);
        }else {
            scanRecord.setId(scanRecord1.getId());
            scanRecord.setScanNum(scanRecord1.getScanNum()+1);
            scanRecord.setUpdateTime(String.valueOf(new Date().getTime()));
            moduleService.updateScanRecord(scanRecord);
        }

        List<Goods> relatedGoodsList;
        String brand = goods.getBrand();
        if(brand == null || brand ==""){
            relatedGoodsList = new ArrayList<>();
        }else{
            relatedGoodsList = goodsService.getRelatedGoods(brand,goods.getGoodsId());
        }
        model.addAttribute("Goods",goods);
        model.addAttribute("User",user);
        //model.addAttribute("CategoryList",categoryList);
        model.addAttribute("CommentList",commentList);
        model.addAttribute("RelatedGoodsList",relatedGoodsList);
        return "/home/viewDetail";
    }

    @RequestMapping("/goOrder")
    public String goOrder(String userId,Model model){
        User user = userService.getUserById(Integer.parseInt(userId));
        List<ReceiptInfo> receiptInfoList = moduleService.getReceiptInfo(user.getUserId());
        List<ShoppingCar> shoppingCarList = moduleService.getCartsByUserId(user.getUserId());
        List<Goods> shoppingCarGoodsList = new ArrayList<>();
        for (ShoppingCar shoppingCar:shoppingCarList
                ) {
            Goods goods = goodsService.getByGoodsId(shoppingCar.getGoodsId());
            shoppingCarGoodsList.add(goods);
        }

        model.addAttribute("User",user);
        model.addAttribute("ReceiptInfoList",receiptInfoList);
        model.addAttribute("ShoppingCarList",shoppingCarList);
        model.addAttribute("ShoppingCarGoodsList",shoppingCarGoodsList);

        return "/home/createOrder";
    }

    @RequestMapping("/addToCart")
    @ResponseBody
    public RequestResult addToCart(HttpServletRequest request){
        RequestResult requestResult = new RequestResult();
        String userId = request.getParameter("userId");
        String goodsId = request.getParameter("goodsId");
        Goods goods = goodsService.getByGoodsId(Integer.parseInt(goodsId));
        ShoppingCar shoppingCar = moduleService.getCartByUserAndGoods(Integer.parseInt(userId),Integer.parseInt(goodsId));
        int result = 0;
        if(shoppingCar != null){
            shoppingCar.setGoodsNum(shoppingCar.getGoodsNum()+1);
            shoppingCar.setTotalFee(shoppingCar.getGoodsNum()*goods.getPrice());
            result = moduleService.updateShoppingCart(shoppingCar);
        }else {
            shoppingCar = new ShoppingCar();
            shoppingCar.setGoodsNum(1);
            shoppingCar.setTotalFee(goods.getPrice());
            shoppingCar.setGoodsId(Integer.parseInt(goodsId));
            shoppingCar.setUserId(Integer.parseInt(userId));
            result = moduleService.addShoppingCart(shoppingCar);
        }
        if(result == 1) {
            requestResult.setStatus(Constants.CART_ADD_SUCCESS);
        }else{
            requestResult.setStatus(Constants.CART_ADD_FAILED);
        }
        return requestResult;
    }

}
